package cn.ekuma.epos.android.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/12/15.
 */
public  abstract class AbstractQueryAsyncTask<T> extends AsyncTask<Object,Integer,List<T>> {
    private ProgressDialog progressDialog;
    private boolean isBack=false;
    boolean exeError=false;
    protected int errorCode=0;

    public AbstractQueryAsyncTask(Context c){
        progressDialog = new ProgressDialog(c,0);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("执行中，请稍后......");
        //    设置setCancelable(false); 表示我们不能取消这个弹出框，等下载完成之后再让弹出框消失
        progressDialog.setCancelable(false);
        //    设置ProgressDialog样式为水平的样式
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //    在onPreExecute()中我们让ProgressDialog显示出来
    }
    public AbstractQueryAsyncTask(){
        this.isBack=true;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        if(!isBack)
           progressDialog.show();
    }
    @Override
    protected List<T> doInBackground(Object... params)
    {
        List<T>  findObjs;
        try
        {
            findObjs=query();
        }
        catch (Exception e)
        {
            exeError=true;
            e.printStackTrace();
            findObjs=new ArrayList<T>();
        }
        finally
        {

        }
        return findObjs;
    }
    protected abstract List<T> query() throws Exception;

    @Override
    protected void onProgressUpdate(Integer... values)
    {
        super.onProgressUpdate(values);
        //    更新ProgressDialog的进度条
        if(!isBack)
           progressDialog.setProgress(values[0]);
    }
    @Override
    protected  void onPostExecute(List<T> result)
     {
         super.onPostExecute(result);
         if(!isBack)
             progressDialog.dismiss();
         if(exeError)
             queryError(errorCode);
         else
             queryResert(result);
        //    使ProgressDialog框消失

    }

    protected abstract void queryResert(List<T> result);

    protected abstract void queryError(int type);
}